<?php
/**
 * @package		Joomla.Cli
 *
 * @copyright	Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

// Make sure we're being called from the command line, not a web interface
if (array_key_exists('REQUEST_METHOD', $_SERVER)) die();

/**
 * This is a CRON script which should be called from the command-line, not the
 * web.
 */

// Set flag that this is a parent file.
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);

error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', 1);

// Load system defines
if (file_exists(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/defines.php'))
{
	require_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/defines.php';
}

if (!defined('_JDEFINES'))
{
	define('JPATH_BASE', dirname(dirname(dirname(dirname(dirname(__FILE__))))));
	require_once JPATH_BASE . '/includes/defines.php';
}

require_once JPATH_LIBRARIES . '/import.php';
require_once JPATH_LIBRARIES . '/cms.php';

// Force library to be in JError legacy mode
JError::$legacy = true;

// Load the configuration
require_once JPATH_CONFIGURATION . '/configuration.php';

require_once JPATH_ADMINISTRATOR . '/components/com_mariageplanner/helpers/finesms.class.php';

/**
 *
 * @package  Joomla.CLI
 * @since    2.5
 */
class SMSCron extends JApplicationCli
{	 
	public function execute()
    {
		$db = JFactory::getDBO();

		jimport('joomla.application.component.helper');
		$component = JComponentHelper::getComponent('com_mariageplanner');

		$params = $component->params;
		
		$this->out('Begin sms sending');
		
		// Параметры взяты со страницы проектов
		$api = new FineSMS ( 'svadba' , '5cd486893822d', false, false);
		
		// запрос баланса
		$this->out( 'Текущий баланс: ' . $api->getBalance (), PHP_EOL );
		
		$tasks = $this->getTasks();
		foreach ($tasks as $task) {		
			
			//$uid = $this->getUid($task->planner_id);
			//$user = JUser::getInstance($uid);
			$mobile = $task->mobile;
			
			// отправка СМС
			$this->out( 'Отправка смс: ' . $api->sendSMS ( $mobile , $task->message , 'SVS' ), PHP_EOL );
			
			// ответ последнего запроса
			$response = $api->getResponse ();
			
			// запрос статуса сообщения
			if(!empty($response) && !empty($response [ 'messages_id' ])) {
				$result = $api->messageStatus ( $response [ 'messages_id' ]);
				foreach ( $result as $message_id => $status ) {
					$this->out( sprintf ( 'Статус сообщения %s: %s' , $message_id , $status ), PHP_EOL );
				}
			}
			
			$this->processed($task->id);
		}
		$this->out('Finish sms sending');
    }    
    
    public function getTasks() {
    	// Create a new query object.
    	$db = JFactory::getDBO();
    	$nullDate	= $db->quote($db->getNullDate());
		$nowDate	= $db->Quote(JFactory::getDate()->toSql());
    
    	$query = $db->getQuery(true);
    	 
    	$query->select('*');
    	$query->from('#__mariageplanner_tasks');
    	$query->where('`state` = 0');
    	$query->where('`sms_state` = 0');
    	$query->where('date');
    	$query->where('('.$nowDate.' >= date AND date != '.$nullDate.')');
    
    	$db->setQuery($query);
    	$result = $db->loadObjectList();
    	return $result;
    }    
    
    public function getUid($planner_id) {
    	// Create a new query object.
    	$db = JFactory::getDBO();
    	$query = $db->getQuery(true);
    
    	$query->select('*');
    	$query->from('#__mariageplanner_user_lnk');
    	$query->where('planner_id = ' . (int)$planner_id);
    
    	$db->setQuery($query);
    	$result = $db->loadObject();
    	return $result->uid;
    }
    
    public function processed($task_id) {
    	$db		= JFactory::getDBO();
    	$query	= $db->getQuery(true);
    	$query->update('#__mariageplanner_tasks');
    	$query->set('sms_state = 1');
    	$query->where('id = ' . (int) $task_id);
    	 
    	$db->setQuery((string) $query);
    	$db->query();
    }
    
}

JApplicationCli::getInstance('SMSCron')->execute();
